package org.elephas.webapp.frontend.component.links;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.string.Strings;
import org.elephas.webapp.frontend.page.blog.BlogPostPage;
import org.elephas.webapp.model.DetachablePostModel;

/**
 * A bookmarkable link to a blog post. If no model is provided, the title of the
 * post is used as a label.
 * 
 * @author Gerolf Seitz
 * 
 */
public class BookmarkableBlogPostLink extends BookmarkablePageLink {
	private static final long serialVersionUID = 1L;

	private DetachablePostModel postModel;

	/**
	 * Constructs the link.
	 * 
	 * @param id
	 *            the component id
	 * @param postModel
	 *            the post
	 */
	public BookmarkableBlogPostLink(String id, DetachablePostModel postModel) {
		super(id, BlogPostPage.class, BlogPostPage
				.constructPageParameters(postModel.getObject()));
		this.postModel = postModel;
	}

	/**
	 * Constructs the link.
	 * 
	 * @param id
	 *            the component id
	 * @param post
	 *            the post
	 * @param label
	 *            the label for the link
	 */
	public BookmarkableBlogPostLink(String id, DetachablePostModel post,
			IModel label) {
		this(id, post);
		setModel(label);
	}

	@Override
	protected void onComponentTagBody(MarkupStream markupStream,
			ComponentTag openTag) {
		String title = getModelObjectAsString();
		title = Strings.isEmpty(title) ? postModel.getObject().getTitle()
				: title;
		replaceComponentTagBody(markupStream, openTag, title);
	}

}
